import { O2mBase } from './o2mbase.js'

export class O2mTree extends O2mBase {
  constructor(payload = {}) {
    super(payload)
  }

  async search_read(domain) {
    // call by m2m node, to get all for add a record
    const fields = Object.keys(this.metadata)
    return this.Model.search_read({ domain, fields })
  }

  _get_arch_sheet(kwargs = {}) {
    const { arch } = this.config
    const { sheet } = arch

    const { parent_info } = kwargs
    const parent_data = this.get_parent_data(parent_info)
    const record = { parent: parent_data }

    const for_view = 'o2m.tree'
    const kws = { for_view, record }
    return this.get_arch_for_node(sheet, kws)
  }

  _get_sheet(kwargs = {}) {
    if (this.check_has_sheet()) {
      return this._get_arch_sheet(kwargs)
    } else {
      const fs = this.Model.get_fields_all(this.fields)
      return Object.keys(fs).reduce((acc, fld) => {
        acc[fld] = {
          ...fs[fld],
          tagname: 'odoofield',
          string: fs[fld].meta.string
        }
        return acc
      }, {})
    }
  }

  get_sheet(kwargs = {}) {
    const children = this._get_sheet(kwargs)
    return {
      children,
      nodename: 'sheet',
      tagname: 'sheet'
    }
  }

  _get_arch_kanban(kwargs = {}) {
    const { arch } = this.config

    if (!arch) {
      console.log('_get_arch_kanban, no arch', this)
      throw 'arch todo'
    }

    const { kanban } = arch

    if (!('kanban' in arch)) {
      console.log('o2m tree kanban todo', arch)
      throw 'kanban todo'
    }

    const { parent_info } = kwargs
    const parent_data = this.get_parent_data(parent_info)
    const record = { parent: parent_data }

    const for_view = 'o2m.tree'
    const kws = { for_view, record }
    return this.get_arch_for_node(kanban, kws)
  }

  _get_kanban(kwargs = {}) {
    return this._get_arch_kanban(kwargs)
  }

  get_kanban(kwargs = {}) {
    const children = this._get_kanban(kwargs)

    const { card_title = {}, card_label = {}, card_value = {} } = children
    return {
      children: { card_title, card_label, card_value },
      nodename: 'kanban',
      tagname: 'kanban'
    }
  }
}
